package com.cxwx.redisdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        //阅读数+1
        redisTemplate.opsForHash().increment("new_" + id, "read", 1);
        //查询点赞数
        Map entries = redisTemplate.opsForHash().entries("new_" + id);//new_id这个对象的所有属性一次性查出
        model.addAllAttributes(entries);
        return "new" + id;
    }

    //点赞 取消点赞
    @GetMapping("/addZan/{id}/{opType}")
    @ResponseBody
    public Long addZan(@PathVariable Integer id, @PathVariable Integer opType) {
        Long countZan;
        if (opType == 1) {
            countZan = redisTemplate.opsForHash().increment("new_" + id, "countZan", 1);
        } else {
            countZan = redisTemplate.opsForHash().increment("new_" + id, "countZan", -1);
        }
        return countZan;
    }

}
